import Koa from 'koa'
import path from 'path'
import helmet from 'koa-helmet'
import statics from 'koa-static'
import router from './routes/routes'
import koaBody from 'koa-body'
import jsonutil from 'koa-json'
import cors from '@koa/cors'
import compose from 'koa-compose'
import compress from 'koa-compress'
import jwt from 'koa-jwt'
import ErrorHandler from './common/ErrorHandler'
import config from './config'
import WebSocketServer from './config/WebSocket'
const app = new Koa()
const ws = new WebSocketServer()
ws.init()
global.ws = ws
const isDevMode = process.env.NODE_ENV !== 'production'

/**
 * 使用koa-compose 集成中间件
 */
const middleware = compose([
  koaBody({
    multipart: true,
    strict: false,
    formidable: {
      keepExtensions: true,
      maxFieldsSize: 5 * 1024 * 1024
    },
    onError (err) {
      console.log(err)
    }
  }),
  statics(path.join(__dirname, '../public')),
  cors(),
  jsonutil({ pretty: false, param: 'pretty' }),
  helmet(),
  ErrorHandler,
  jwt({
    secret: config.JWT_SECRET
  }).unless({ path: [/^\/public/, /^\/login/] })
])

if (!isDevMode) {
  app.use(compress())
}
const port = !isDevMode ? 12005 : 3000
app.use(middleware)
app.use(router())

app.listen(port, () => {
  console.log(`The server is running at:${port}`)
})
